package com.client.controller;

import com.Emplyment.entity.UserRegister;
import com.Emplyment.exception.BaseException;
import com.Emplyment.properties.JwtProperties;
import com.Emplyment.result.Result;
import com.Emplyment.utils.jwtUtils;
import com.Emplyment.vo.ArticleVo;
import com.Emplyment.vo.ClientUserInfosVo;
import com.Emplyment.vo.EmplyeeLoginVo;
import com.client.service.ClientFirstPageService;
import com.client.service.ClientUserService;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/client")
public class ClientUserController {

    @Autowired
    private ClientUserService clientUserService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private ClientFirstPageService clientFirstPageService;

    @GetMapping("/sendEmail")
    public Result sendEmail(@RequestParam String email, @RequestParam String code){
        log.info("获取到发送邮件的邮箱:{}, 类型为：{}", email,code);
        Integer result = clientUserService.sendEmail(email, code);
        if (result == 1){
            return Result.success("发送成功");
        } else if (result == 2) {
            return Result.error("1分钟内只能发送一次");
        }else if (result == 3){
            return Result.error("一个邮箱账户一天内只能发送5次");
        } else if (result == 4) {
            return Result.error("邮箱不存在,请重新输入");
        }
        return Result.error("验证码发送失败");
    }

    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestParam String email, @RequestParam String newPassword, @RequestParam String verifyCode) {
        log.info("获取到重置密码的邮箱:{}, 密码:{}, 验证码:{}", email, newPassword, verifyCode);
        Integer result = clientUserService.resetPassword(email, newPassword, verifyCode);
        if (result == 1) {
            return Result.error("密码或者邮箱或者验证码为空请重新输入");
        } else if (result == 2) {
            return Result.error("验证码过期");
        } else if (result == 3) {
            return Result.error("验证码错误,请重新输入");
        } else if (result == 4) {
            return Result.error("账户不存在,请重新输入");
        }
        return Result.success();
    }

    @PostMapping("/register")
    public Result register(@RequestParam String username, @RequestParam String password,
                           @RequestParam String email, @RequestParam String verifyCode) {
        log.info("获取到注册的用户名:{},获取到的注册密码:{},获取到的注册邮箱:{},获取到的验证码:{}", username, password,email,verifyCode);
        if (username.isEmpty() || password.isEmpty()){
            return Result.error("用户名或密码为空");
        }
        Integer result = clientUserService.clientUserRegistration(username, password, email, verifyCode);
        if (result == 1){
            return Result.error("用户名或者密码为空请重新注册");
        } else if (result == 2) {
            return Result.error("验证码过期");
        } else if (result == 3) {
            return Result.error("验证码错误,请重新输入");
        } else if (result == 4) {
            return Result.error("用户名已存在,请重新注册");
        } else if (result == 5) {
            return Result.error("邮箱已存在,请重新注册");
        }
        return Result.success();
    }

    @PostMapping("/login")
    public Result<EmplyeeLoginVo> login(@RequestParam String username, @RequestParam String password) {
        log.info("获取到登录的用户名:{},获取到的登录密码:{}", username, password);
        UserRegister userRegister = clientUserService.clientUserLogin(username, password);

        //登录成功，生成jwt令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put("user_id",userRegister.getId());
        String token = jwtUtils.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims
        );

        EmplyeeLoginVo emplyeeLoginVo = new EmplyeeLoginVo();
        BeanUtils.copyProperties(userRegister,emplyeeLoginVo);
        emplyeeLoginVo.setToken(token);

        return Result.success(emplyeeLoginVo);
    }

    @GetMapping("/advertisement")
    public Result<List<String>> getAdvertisement(){
        List<String> advertisement = clientFirstPageService.getAdvertisement();
        log.info("获取到广告:{}", JSONObject.toJSONString(advertisement));
        return Result.success(advertisement);
    }

    @GetMapping("/employment")
    public Result<List<Map<String,String>>> getEmployment(){
        List<Map<String, String>> clientFirstPageServiceEmployment = clientFirstPageService.getEmployment();
        log.info("获取到公司信息:{}", JSONObject.toJSONString(clientFirstPageServiceEmployment));
        return Result.success(clientFirstPageServiceEmployment);
    }

    @GetMapping("/userInfo")
    public Result<ClientUserInfosVo> getUserInfo(@RequestHeader String token){
        log.info("获取到token:{}", token);
        ClientUserInfosVo clientUserInfosVo = new ClientUserInfosVo();
        try {
            Claims claims = jwtUtils.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long userId = Long.valueOf(claims.get("user_id").toString());
            clientUserInfosVo = clientUserService.getUserInfo(userId);
            log.info("获取到用户信息:{}", JSONObject.toJSONString(clientUserInfosVo));
        } catch (Exception e) {
            throw new BaseException("登录过期、请重新登录");
        }
        return Result.success(clientUserInfosVo);
    }

    /**
     * 点击公司详情后调用页面传回的数据
     * @param empId
     * @return
     */
    @GetMapping("/getCompany/{empId}")
    public Result<ArticleVo> getCompany(@PathVariable("empId") Integer empId){
        log.info("获取到empId:{}", empId);
        ArticleVo company = clientUserService.getCompany(empId);
        log.info("获取到公司信息:{}", JSONObject.toJSONString(company));
        return Result.success(company);
    }
}
